package com.epoch.zuul.auth.token;

import com.epoch.zuul.auth.dao.ConsumerDao;
import com.epoch.zuul.auth.dao.CsRoleDao;
import com.epoch.zuul.auth.role.Consumer;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @PackageName:com.ye.shiro.realm
 * @ClassName:MyRealm
 * @Description:
 * @date:2021/4/30 10:58
 */
@Component
public class MyRealm extends AuthorizingRealm {

//    @Autowired
//    private ConsumerService consumerService;
    @Autowired
    private ConsumerDao consumerDao;

    @Autowired
    private CsRoleDao csRoleDao;


    /**
     * 获得自己定义的token
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.iterator().next();
        Set<String> roleNames = csRoleDao.getRoleNameByCsPhone(username);
        Set<String> permission = csRoleDao.getAllAuthByCsPhone(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        System.out.println("当前授权用户["+username+"]的身份为："+roleNames);
        info.setRoles(roleNames);
        info.setStringPermissions(permission);
        return info;
    }

    /**
     * 使用自定义token
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        String token = (String) jwtToken.getPrincipal();
        Claims claims = JwtUtil.parseJWT(token);
        String username = claims.getId();
        Consumer consumer = consumerDao.getByCsPhone(username);
        if (consumer == null){
            return null;
        }
        return new SimpleAuthenticationInfo(username, consumer.getCsPwd(), getName());
    }

}
